// axios 二次封装   requset.js api.js http.js
import axios from 'axios'
import Qs from 'qs'
// import { token } from './tool'
// 导入elementui 的提示插件 
import { MessageBox } from 'element-ui'


axios.defaults.withCredentials = true//axios 全局配置可跨域  true跨域 false不跨域
// headerType  json  multipart  form
export default function (path, params, method = "GET", headerType) {
  let data = {};
  // 1.在axios的请求拦截器中不同的请求方式 配置不同的请求头 post请求qs转换参数
  if (method == "post") {
    if (headerType == "json") {
      axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"
      data = params;
    } else if (headerType == "multipart") {
      //完成上传操作使用的请求头
      data = params;
      axios.defaults.headers.post["Content-Type"] = "multipart/form-data"
    } else {
      // 表单形式的请求头 要把传入的json 序列化 name=1&age=2
      axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
      data = Qs.stringify(params)
    }
  }
  if (method === "get") {
    axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
    data = params
  }
  // axios 请求拦截器
  axios.interceptors.request.use(config => {
    // if (token()) {
    //   config.headers["token"] = token()
    // } else {
    //   // hash  history
    //   location.href = "/login";
    // }
    return config
  })
  // axios 响应拦截器
  axios.interceptors.response.use(response => {
    if (response.status == 404) {
      MessageBox.alert("路径错误")
    }
    if (response.status == 500) {
      MessageBox.alert("后端服务器错误或未启动")
    }
    return response
  }, err => {
    MessageBox.alert("预期之外的错误");
    return Promise.reject(err.response)
  })
  // 
  return new Promise((resolve, reject) => {
    if (method == "get") {
      axios({
        url: path,
        method,
        timeout: 6000,
        params: data
      }).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    } else {
      axios({
        url: path,
        method,
        timeout: 6000,
        data: data
      }).then(res => {
        resolve(res.data)
      }).catch(err => {
        reject(err)
      })
    }
  })
}
